package com.cuz.series.linklist;

/**
 * https://leetcode.cn/problems/swap-nodes-in-pairs/submissions/
 */
public class 链表11K个一组翻转链表 {

    public static void main(String[] args) {
        ListNode listNode = ListNode.of1(1, 2, 3, 4, 5, 6, 7);
        ListNode listNode1 = reverseKGroup1(listNode, 3);
        listNode1.print();
        ;
    }

    public static ListNode reverseKGroup1(ListNode head, int k) {
        if (head == null || head.next == null || k == 1) {
            return head;
        }
        int len = len(head);
        if (len < k) {
            return head;
        }

        ListNode preHead = new ListNode();
        ListNode tail = preHead;
        int needReverse = len / k;
        for (int i = 0; i < needReverse; i++) {
            ListNode temp = unlinkReturnNext(head, k);
            ListNode[] nodes = reverseReturnHeadTail(head);
            ListNode newHead = nodes[0];
            ListNode newTail = nodes[1];
            tail.next = newHead;
            tail = newTail;
            head = temp;
        }
        tail.next=head;
        return preHead.next;
    }
    public static ListNode[] reverseReturnHeadTail(ListNode head) {
        ListNode preHead = new ListNode();
        preHead.next = head;
        ListNode cur = head.next;
        head.next = null;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = preHead.next;
            preHead.next=cur;
            cur=temp;
        }
        return new ListNode[]{preHead.next, head};
    }


    private static ListNode unlinkReturnNext(ListNode node, int k) {
        for (int i = 1; i < k; i++) {
            node = node.next;
        }
        ListNode next = node.next;
        node.next = null;
        return next;
    }

    private static int len(ListNode node) {
        if (node == null) {
            return 0;
        }
        int len = 0;
        while (node != null) {
            len++;
            node = node.next;
        }
        return len;
    }
}
